using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Navigation;
using Lib.Approval;
using Lib.Helper;
using Lib.Mail;
using MSIACCSL2.ApplicationStateServices;
using MSIACCSL2.Command;
using MSIACCSL2.InventoryServices;
using MSIACCSL2.MutasiWarehouseServices;
using MSIACCSL2.Views.MutasiWarehouse;
using MSIACCSL2.WarehouseServices;
using WcfService1.DTO;
using GetListByCriteriaCompletedEventArgs = MSIACCSL2.MutasiWarehouseServices.GetListByCriteriaCompletedEventArgs;
using GetListCompletedEventArgs = MSIACCSL2.MutasiWarehouseServices.GetListCompletedEventArgs;
using SaveCompletedEventArgs = MSIACCSL2.MutasiWarehouseServices.SaveCompletedEventArgs;

namespace MSIACCSL2.ViewModels
{
    public class MutasiWarehouseViewModel : ViewModelBase
    {
        #region Delegates

        public delegate void Completed(Object param);

        #endregion

        private static Search frmSearch;
        private static string OrderType;
        private static string PropertySort;
        public static Mode mode;
        public static Completed OnSearchCompleted;
        private readonly AplicationStateServicesClient ApplicationService;


        private int CurrentPage;
        private WarehouseServicesClient FromWarehouseClient;
        private bool IsUsed;
        private ObservableCollection<int> Pages;
        private WarehouseServicesClient ToWarehouseClient;
        private ObservableCollection<WarehouseDTO> _FromWarehouses;
        private bool _IsBusy;
        private bool _IsEnabled;
        private MutasiWarehouseDTO _MutasiWarehouse;
        private PagedCollectionView _MutasiWarehouses;
        private ObservableCollection<WarehouseDTO> _ToWarehouses;
        private List<string> _errors;
        private Visibility _messageVisibility;
        private PagedCollectionView _pageSources;
        private MutasiWarehouseServicesClient client;
        private InventoryServiceClient InventoryClient;

        public MutasiWarehouseViewModel()
        {
            
            if (!DesignerProperties.IsInDesignTool)
            {
                IsEnabled = true;
                client = new MutasiWarehouseServicesClient();
                OnPageChanged = new DelegateCommand(PageIndexChanged, CanPageIndexChanged);
                Save = new DelegateCommand(SaveMutasiWarehouse, CanSave);
                New = new DelegateCommand(NewMutasiWarehouse, CanNew);
                Unload = new DelegateCommand(Release, CanUnload);
                SearchCommand = new DelegateCommand(SearchMutasiWarehouse, CanSearch);
                SearchResultCommand = new DelegateCommand(SearchResult, CanSearchResult);
                CancelCommand = new DelegateCommand(Cancel, CanCancelCommand);
                new ValidationHandler();
                MessageVisibility = Visibility.Collapsed;
                Errors = new List<string>();
                ApplicationService = new AplicationStateServicesClient();
                InventoryClient = new InventoryServiceClient();
                if (mode == Mode.Edit)
                {
                    GetFromWarehouseList();
                    GetToWarehouseList();
                    MutasiWarehouse = (MutasiWarehouseDTO) Navigation.Args;
                    LoadMutasiWarehouse();
                    if (MutasiWarehouse.MutasiWarehouseDetails == null)
                        MutasiWarehouse.MutasiWarehouseDetails = new ObservableCollection<MutasiWarehouseDetailDTO>();
                    if (MutasiWarehouse.MutasiWarehouseDetails.Count == 0)
                        MutasiWarehouse.MutasiWarehouseDetails.Add(new MutasiWarehouseDetailDTO());
                    CekTransaksi();
                }
                else if (mode == Mode.Search)
                {
                    MutasiWarehouse = new MutasiWarehouseDTO();
                    MutasiWarehouse.TglMutasi = null;
                    GetFromWarehouseList();
                    GetToWarehouseList();
                }
                else if (mode == Mode.Add)
                {
                    //GetLastNoMutasi();
                    GetFromWarehouseList();
                    GetToWarehouseList();
                    MutasiWarehouse = new MutasiWarehouseDTO();
                    MutasiWarehouse.MutasiWarehouseDetails = new ObservableCollection<MutasiWarehouseDetailDTO>();
                    var MutasiWarehouseDetail = new MutasiWarehouseDetailDTO();
                    MutasiWarehouseDetail.Inventory = new InventoryDTO();
                    MutasiWarehouse.MutasiWarehouseDetails.Add(MutasiWarehouseDetail);
                    //CekTransaksi();
                }
                else
                {
                    GetList(1, null);
                }
            }
        }


        public void LoadMutasiWarehouse()
        {
            IsBusy = true;
            client.GetMutasiWarehouseCompleted += new EventHandler<GetMutasiWarehouseCompletedEventArgs>(client_GetMutasiWarehouseCompleted);
            client.GetMutasiWarehouseAsync(MutasiWarehouse.NoMutasi);
        }


        void client_GetMutasiWarehouseCompleted(object sender, GetMutasiWarehouseCompletedEventArgs e)
        {
            client.GetMutasiWarehouseCompleted -= new EventHandler<GetMutasiWarehouseCompletedEventArgs>(client_GetMutasiWarehouseCompleted);
            MutasiWarehouse = e.Result;
            IsBusy = false;
        }

        public PagedCollectionView MutasiWarehouses
        {
            get { return _MutasiWarehouses; }

            private set
            {
                if (MutasiWarehouses == value) return;
                _MutasiWarehouses = value;
                int i = (CurrentPage*30);
                foreach (object MutasiWarehouse in MutasiWarehouses)
                {
                    i += 1;

                    ((MutasiWarehouseDTO) MutasiWarehouse).No = i;
                }
                FirePropertyChanged("MutasiWarehouses");
                MutasiWarehouses.CollectionChanged += MutasiWarehouse_CollectionChanged;
            }
        }


        public PagedCollectionView PageSources
        {
            get { return _pageSources; }
            private set
            {
                if (PageSources == value) return;
                _pageSources = value;
                FirePropertyChanged("PageSources");
            }
        }


        public ObservableCollection<WarehouseDTO> FromWarehouses
        {
            get { return _FromWarehouses; }
            private set
            {
                if (FromWarehouses == value) return;
                _FromWarehouses = value;
                FirePropertyChanged("FromWarehouses");
            }
        }


        public ObservableCollection<WarehouseDTO> ToWarehouses
        {
            get { return _ToWarehouses; }
            private set
            {
                if (ToWarehouses == value) return;
                _ToWarehouses = value;
                FirePropertyChanged("ToWarehouses");
            }
        }


        public bool IsBusy
        {
            get { return _IsBusy; }
            internal set
            {
                _IsBusy = value;
                FirePropertyChanged("IsBusy");
            }
        }


        public long RecordCount { get; set; }

        //Buat binding ke child form waktu mau edit
        public MutasiWarehouseDTO MutasiWarehouse
        {
            get { return _MutasiWarehouse; }
            private set
            {
                if (MutasiWarehouse == value) return;
                _MutasiWarehouse = value;
                FirePropertyChanged("MutasiWarehouse");
            }
        }


        public ICommand OnPageChanged { get; set; }
        public ICommand Save { get; set; }
        public ICommand New { get; set; }
        public ICommand Edit { get; set; }
        public ICommand Unload { get; set; }
        public ICommand SearchCommand { get; set; }
        public ICommand SearchResultCommand { get; set; }
        public ICommand CancelCommand { get; set; }

        public List<string> Errors
        {
            get { return _errors; }
            private set
            {
                if (Errors == value) return;
                _errors = value;
                FirePropertyChanged("Errors");
            }
        }

        public Visibility MessageVisibility
        {
            get { return _messageVisibility; }
            private set
            {
                if (MessageVisibility == value) return;
                _messageVisibility = value;
                FirePropertyChanged("MessageVisibility");
            }
        }

        public bool IsEnabled
        {
            get { return _IsEnabled; }
            internal set
            {
                _IsEnabled = value;
                FirePropertyChanged("IsEnabled");
            }
        }

        public void Complete(Object param)
        {
            OnSearchCompleted(param);
        }

        private void MutasiWarehouse_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (((PagedCollectionView) sender).SortDescriptions.Count > 0)
            {
                if (((PagedCollectionView) sender).SortDescriptions[0].PropertyName.ToLower() == "no") return;

                PropertySort = ((PagedCollectionView) sender).SortDescriptions[0].PropertyName;
                if (string.IsNullOrEmpty(OrderType))
                {
                    OrderType = "ASC";
                }
                else
                {
                    OrderType = OrderType == "ASC" ? OrderType = "DESC" : OrderType = "ASC";
                }
                GetList(1, PropertySort);
            }
        }


        public void SaveMutasiWarehouse(Object mutasiwarehouse)
        {
            //MutasiWarehouse = (MutasiWarehouseDTO) mutasiwarehouse;
            if (MutasiWarehouse.MutasiWarehouseDetails.Count == 1)
            {
                //Bila tidak ada yang dipilih di detail maka details harus dihapus
                if (MutasiWarehouse.MutasiWarehouseDetails[0].Inventory == null)
                    MutasiWarehouse.MutasiWarehouseDetails.Clear();
            }
            Validate();
            if (Errors.Count > 0) return;
            MutasiWarehouse.created_by = GlobalVar.User.UserID;
            MutasiWarehouse.modified_by = GlobalVar.User.UserID;
            IsBusy = true;
            client.SaveCompleted += client_SaveCompleted;
            client.SaveAsync(MutasiWarehouse, mode);
        }

        private void client_SaveCompleted(object sender, SaveCompletedEventArgs e)
        {
            if (e.Error != null) Validate(e.Error.ToString());
            client.SaveCompleted -= client_SaveCompleted;
            mode = (Mode) e.UserState;
            if (e.Result)
            {
                IsBusy = false;
                ClearTransaksi(mode);
                mode = Mode.Idle;
                Navigation.MyNavigation.Navigate(new Uri("/MutasiWarehouse/Index", UriKind.Relative));
            }
            else
            {
                IsBusy = false;
                if (e.Error != null)
                    MessageBox.Show(e.Error.Message);
            }
        }


        private void client_SaveMutasiWarehouseCompleted(object sender, SaveCompletedEventArgs e)
        {
            if (e.Error != null) Validate(e.Error.ToString());
            client.SaveCompleted -= client_SaveMutasiWarehouseCompleted;
            if (e.Result)
            {
                MessageBox.Show("Success");
                Refresh();
            }
        }


        public void GetList(int? page, string sortProp)
        {
            IsBusy = true;
            client.GetListCompleted += client_GetListCompleted;
            client.GetListAsync(page ?? 1, sortProp, OrderType);
        }

        private void client_GetListCompleted(object sender, GetListCompletedEventArgs e)
        {
            RecordCount = e.recordCount;
            if (PageSources == null) CreatePageNumber();
            client.GetListCompleted -= client_GetListCompleted;
            MutasiWarehouses = new PagedCollectionView(e.Result);
            IsBusy = false;
            Complete(this);
        }


        private void NewMutasiWarehouse(Object param)
        {
            mode = Mode.Add;
            Navigation.MyNavigation = (NavigationService) param;
            Navigation.MyNavigation.Navigate(new Uri("/MutasiWarehouse/frmAdd", UriKind.Relative));
        }


        private void SearchMutasiWarehouse(Object param)
        {
            mode = Mode.Search;
            frmSearch = new Search();
            frmSearch.Show();
        }


        private void SearchResult(Object param)
        {
            var criteria = new Dictionary<string, object>();

            foreach (PropertyInfo prop in MutasiWarehouse.GetType().GetProperties())
            {
                if (prop.PropertyType == typeof (Decimal))
                {
                    if ((Decimal) prop.GetValue(MutasiWarehouse, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Int32))
                {
                    if ((Int32) prop.GetValue(MutasiWarehouse, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Int64))
                {
                    if ((Int64) prop.GetValue(MutasiWarehouse, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Double))
                {
                    if ((Double) prop.GetValue(MutasiWarehouse, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (String))
                {
                    if (String.IsNullOrEmpty((String) prop.GetValue(MutasiWarehouse, null))) continue;
                }
                if (prop.PropertyType == typeof (DateTime))
                {
                    if (prop.GetValue(MutasiWarehouse, null).ToString().Contains("0001")) continue;
                }
                if (prop.GetValue(MutasiWarehouse, null) == null) continue;
                if (prop.PropertyType.Name == "No") continue;

                if (prop.PropertyType.Name.ToLower().Contains("dto"))
                {
                    foreach (PropertyInfo propertyInfo in prop.GetValue(MutasiWarehouse, null).GetType().GetProperties()
                        )
                    {
                        if (propertyInfo.Name.ToLower().Contains("id") || propertyInfo.Name.ToLower().Contains("kode") ||
                            propertyInfo.Name.ToLower().Contains("serial") ||
                            propertyInfo.Name.ToLower().Contains("code"))
                        {
                            criteria.Add(prop.Name, propertyInfo.GetValue(prop.GetValue(MutasiWarehouse, null), null));
                            break;
                        }
                    }
                }
                else
                {
                    criteria.Add(prop.Name, prop.GetValue(MutasiWarehouse, null));
                }
            }

            string expression = string.Empty;
            if (frmSearch.rblOr.IsChecked ?? false) expression = "OR";
            else expression = "AND";
            MutasiWarehouseSearch(criteria, expression);
        }

        private void MutasiWarehouseSearch(Dictionary<String, Object> criteria, string expression)
        {
            frmSearch.DialogResult = true;
            IsBusy = true;
            Complete(this);
            client.GetListByCriteriaCompleted += client_GetListByCriteriaCompleted;
            client.GetListByCriteriaAsync(criteria, expression, 1);
        }

        private void client_GetListByCriteriaCompleted(object sender, GetListByCriteriaCompletedEventArgs e)
        {
            client.GetListByCriteriaCompleted -= client_GetListByCriteriaCompleted;
            MutasiWarehouses = new PagedCollectionView(e.Result);
            RecordCount = e.recordCount;
            CreatePageNumber();
            IsBusy = false;
        }


        private void GetFromWarehouseList()
        {
            FromWarehouseClient = new WarehouseServicesClient();
            FromWarehouseClient.GetAllWarehouseCompleted +=
                FromWarehouseClient_GetAllFromWarehouseCompleted;
            FromWarehouseClient.GetAllWarehouseAsync();
        }

        private void FromWarehouseClient_GetAllFromWarehouseCompleted(object sender,
                                                                      GetAllWarehouseCompletedEventArgs e)
        {
            FromWarehouseClient.GetAllWarehouseCompleted -=
                FromWarehouseClient_GetAllFromWarehouseCompleted;
            FromWarehouses = e.Result;
            if (MutasiWarehouse != null)
            {
                if (MutasiWarehouse.FromWarehouse == null) return;
                MutasiWarehouse.FromWarehouse =
                    FromWarehouses.FirstOrDefault(
                        s => s.KodeWarehouse == MutasiWarehouse.FromWarehouse.KodeWarehouse);
            }
        }

        private void GetToWarehouseList()
        {
            ToWarehouseClient = new WarehouseServicesClient();
            ToWarehouseClient.GetAllWarehouseCompleted +=
                ToWarehouseClient_GetAllToWarehouseCompleted;
            ToWarehouseClient.GetAllWarehouseAsync();
        }

        private void ToWarehouseClient_GetAllToWarehouseCompleted(object sender,
                                                                  GetAllWarehouseCompletedEventArgs
                                                                      e)
        {
            ToWarehouseClient.GetAllWarehouseCompleted -=
                ToWarehouseClient_GetAllToWarehouseCompleted;
            ToWarehouses = e.Result;
            if (MutasiWarehouse != null)
            {
                if (MutasiWarehouse.ToWarehouse == null) return;
                MutasiWarehouse.ToWarehouse =
                    ToWarehouses.FirstOrDefault(s => s.KodeWarehouse == MutasiWarehouse.ToWarehouse.KodeWarehouse);
            }
        }


        private void CreatePageNumber()
        {
            Pages = new ObservableCollection<int>();
            for (int i = 0; i < RecordCount; i++)
            {
                Pages.Add(i);
            }
            PageSources = new PagedCollectionView(Pages);
        }


        private void PageIndexChanged(Object pageIndex)
        {
            //Jika Pertama kali jangan di Getlagi
            MutasiWarehouse = null;
            if (MutasiWarehouses != null && CurrentPage != (int) pageIndex)
            {
                CurrentPage = (int) pageIndex;
                if (String.IsNullOrEmpty(PropertySort))
                    GetList((int) pageIndex + 1, null);
                else GetList((int) pageIndex + 1, PropertySort);
            }
        }


        public bool CanPageIndexChanged(Object param)
        {
            return true;
        }


        public bool CanSave(Object param)
        {
            return true;
        }


        public bool CanNew(Object param)
        {
            return true;
        }

        public bool CanEdit(Object param)
        {
            return true;
        }


        public bool CanUnload(Object param)
        {
            return true;
        }


        public bool CanSearch(Object param)
        {
            return true;
        }

        public bool CanSearchResult(Object param)
        {
            return true;
        }

        public bool CanCancelCommand(Object param)
        {
            return true;
        }


        public void Release(Object param)
        {
            param = null;
            MutasiWarehouse = null;
            OrderType = null;
            PropertySort = null;
            mode = Mode.Idle;
        }


        public void Refresh()
        {
            if (MutasiWarehouses == null)
                GetList(1, null);
            else
                Complete(this);
        }


        public void Validate(string error = null)
        {
            Errors = new List<string>();
            //if (string.IsNullOrEmpty(MutasiWarehouse.NoMutasi))
            //    Errors.Add("Nomor Mutasi tidak boleh kosong");

            //validasi detail
            //foreach (MutasiWarehouseDetailDTO mutasiWarehouseDetail in MutasiWarehouse.MutasiWarehouseDetails)
            //{
            //    if (mutasiWarehouseDetail.Inventory.InventoryWarehouses.Any(x=>x.Warehouse.KodeWarehouse == MutasiWarehouse.FromWarehouse.KodeWarehouse))
            //        Errors.Add(mutasiWarehouseDetail.Inventory.SerialNumber + " tidak berada pada Warehouse " +
            //                   MutasiWarehouse.FromWarehouse.KodeWarehouse);
            //}

            if (!string.IsNullOrEmpty(error))
                Errors.Add(error);

            if (Errors.Count > 0)
            {
                MessageVisibility = Visibility.Visible;
            }
            else
            {
                MessageVisibility = Visibility.Collapsed;
            }
        }

        public void Cancel(Object param)
        {
            MessageBoxResult res = MessageBox.Show("Are You Sure Want to Cancel ?", "Confirmation",
                                                   MessageBoxButton.OKCancel);
            if (res == MessageBoxResult.OK)
            {
                if (!IsUsed) ClearTransaksi(mode);
                mode = Mode.Idle;
                Navigation.MyNavigation.GoBack();
            }
        }

        private void GetLastNoMutasi()
        {
            client = new MutasiWarehouseServicesClient();
            client.GetLastNoMutasiCompleted += client_GetLastNoMutasiCompleted;
            client.GetLastNoMutasiAsync();
        }

        private void client_GetLastNoMutasiCompleted(object sender, GetLastNoMutasiCompletedEventArgs e)
        {
            client.GetLastNoMutasiCompleted -= client_GetLastNoMutasiCompleted;
            string res = e.Result;
            string formatSO = "0000";
            string kodeSO;
            if (e.Result.Length <= 4)
            {
                res = formatSO;
                kodeSO = e.Result;
            }
            else
            {
                res = e.Result.Split(new[] {"/"}, StringSplitOptions.RemoveEmptyEntries)[2];
                kodeSO = e.Result.Split(new[] {"/"}, StringSplitOptions.RemoveEmptyEntries)[0];
            }
            string soNum = formatSO.Substring(0, formatSO.Length - (int.Parse(res) + 1).ToString().Length) +
                           (int.Parse(res) + 1);

            //MutasiWarehouse = new MutasiWarehouseDTO();
            MutasiWarehouse.NoMutasi = kodeSO + "/" + DateTime.Now.Year + "/" + soNum;
        }

        private void AddMutasiWarehouseDetail()
        {
            MutasiWarehouse.MutasiWarehouseDetails.Add(new MutasiWarehouseDetailDTO());
        }

        public void SendEmail(Object param)
        {
            ChooseDestination chooseDestination = new ChooseDestination();
            chooseDestination.Show();
            EventAggregator.RegisterMessage("SendDestination", (x) =>
            {
                IsBusy = true;
                client.SendEmailCompleted += client_SendEmailCompleted;
                client.SendEmailAsync(param as MutasiWarehouseDTO, (x as WarehouseDTO).EmailFolder);
            });
        }

        private void client_SendEmailCompleted(object sender, SendEmailCompletedEventArgs e)
        {
            IsBusy = false;
            client.SendEmailCompleted -= client_SendEmailCompleted;
            if (e.Result) MessageBox.Show("Pengiriman Selesai");
        }

        public void CekTransaksi()
        {
            ApplicationService.IsTransactionUsedCompleted += ApplicationService_IsTransactionUsedCompleted;
            if (string.IsNullOrEmpty(MutasiWarehouse.NoMutasi))
            {
                ApplicationService.IsTransactionUsedAsync(MutasiWarehouse.ToString(), GlobalVar.User, mode);
                GlobalVar.CurrentTransaction = MutasiWarehouse.ToString();
            }
            else
            {
                ApplicationService.IsTransactionUsedAsync(MutasiWarehouse.NoMutasi, GlobalVar.User, mode);
                GlobalVar.CurrentTransaction = MutasiWarehouse.NoMutasi;
            }
        }

        private void ApplicationService_IsTransactionUsedCompleted(object sender, IsTransactionUsedCompletedEventArgs e)
        {
            ApplicationService.IsTransactionUsedCompleted -= ApplicationService_IsTransactionUsedCompleted;
            IsUsed = e.Result;
            mode = (Mode) e.UserState;
            if (IsUsed)
            {
                MessageBox.Show("Transaksi sedang digunakan!");
                if (mode == Mode.Add) //If Add Mode
                {
                    mode = Mode.Idle;
                    Navigation.MyNavigation.Navigate(new Uri("/MutasiWarehouse/Index", UriKind.Relative));
                }
                else //Edit Mode just view Only
                {
                    IsEnabled = false;
                }
            }
        }

        private void ClearTransaksi(Mode mode)
        {
            ApplicationService.ClearTransactionCompleted += ApplicationService_ClearTransactionCompleted;
            if (mode == Mode.Add)
                ApplicationService.ClearTransactionAsync(MutasiWarehouse.ToString(), GlobalVar.User);
            else
                ApplicationService.ClearTransactionAsync(MutasiWarehouse.NoMutasi, GlobalVar.User);
        }

        private void ApplicationService_ClearTransactionCompleted(object sender, AsyncCompletedEventArgs e)
        {
            ApplicationService.ClearTransactionCompleted -= ApplicationService_ClearTransactionCompleted;
        }

        public void CloseStatus()
        {
            MessageBoxResult res = MessageBox.Show("Are You Sure Want to Close this Transaction ?", "Confirmation",
                                                MessageBoxButton.OKCancel);
            if (res == MessageBoxResult.OK)
            {
                client.UpdateStatusCompleted += new EventHandler<AsyncCompletedEventArgs>(client_UpdateStatusCompleted);
                client.UpdateStatusAsync(MutasiWarehouse, Status.Close);
            }
        }

        void client_UpdateStatusCompleted(object sender, AsyncCompletedEventArgs e)
        {
            client.UpdateStatusCompleted -= new EventHandler<AsyncCompletedEventArgs>(client_UpdateStatusCompleted);
            MessageBox.Show("Update Status finished!");
        }

        public void LoadDetailFromFile(Object param)
        {
            ImportHelper importHelper = new ImportHelper();
            IEnumerable<List<dynamic>> sourcesOld;
            importHelper.BrowseExcelFile(out sourcesOld);
            var sources = importHelper.LoadExcellFile(importHelper.listSheetNames.FirstOrDefault());
          
            ObservableCollection<InventoryDTO> inventoryDtos = new ObservableCollection<InventoryDTO>();

            if (sourcesOld == null || sourcesOld.Count() == 0)
            {
                if (sources != null)
                    foreach (dynamic data in sources)
                    {
                        string noLog = data.A;
                        if (string.IsNullOrEmpty(noLog)) continue;
                        inventoryDtos.Add(new InventoryDTO() { SerialNumber = noLog });
                    }
            }
            else
            {
                int i = 0;
                foreach (var data in sourcesOld)
                {
                    if (i > 0)
                    {
                        string noLog = data[0];
                        if (string.IsNullOrEmpty(noLog)) continue;
                        inventoryDtos.Add(new InventoryDTO() { SerialNumber = noLog });
                    }
                    i++;
                }
            }

            if (inventoryDtos.Count > 0)
                GetInventoryList(inventoryDtos);
        }

        public void GetInventoryList(ObservableCollection<InventoryDTO> inventoryDtos)
        {
            InventoryClient.GetInventoryListCompleted += new EventHandler<GetInventoryListCompletedEventArgs>(InventoryClient_GetInventoryListCompleted);
            InventoryClient.GetInventoryListAsync(inventoryDtos);
        }

        void InventoryClient_GetInventoryListCompleted(object sender, GetInventoryListCompletedEventArgs e)
        {
            InventoryClient.GetInventoryListCompleted -= new EventHandler<GetInventoryListCompletedEventArgs>(InventoryClient_GetInventoryListCompleted);
            foreach (var InventoryTemp in e.Result)
            {
                var MutasiWarehouseDetail = new MutasiWarehouseDetailDTO();
                try
                {
                    MutasiWarehouseDetail.Inventory = InventoryTemp;
                    MutasiWarehouseDetail.Inventory.Item =
                        InventoryTemp.Item;
                    MutasiWarehouseDetail.Inventory.SatuanUnit =
                        InventoryTemp.SatuanUnit;
                    MutasiWarehouseDetail.Sheet = InventoryTemp.Warehouses.FirstOrDefault
                  (x => x.KodeWarehouse == MutasiWarehouse.FromWarehouse.KodeWarehouse).Sheet;
                    MutasiWarehouseDetail.Qty = InventoryTemp.Warehouses.FirstOrDefault
                    (x => x.KodeWarehouse == MutasiWarehouse.FromWarehouse.KodeWarehouse).Qty;
                    MutasiWarehouseDetail.Panjang = InventoryTemp.Panjang;
                    MutasiWarehouseDetail.Lebar = InventoryTemp.Lebar;
                    MutasiWarehouse.MutasiWarehouseDetails.Add(MutasiWarehouseDetail);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Invalid Mutasi, Warehouse dan Stok tidak match!");
                }
            }
        }
    }


    public class MutasiWarehouseWrapViewModel : ViewModelBase
    {
        private readonly MutasiWarehouseServicesClient client;
        private InventoryServiceClient InventoryClient;
        private ObservableCollection<InventoryDTO> _Inventorys;
        private MutasiWarehouseDetailDTO _MutasiWarehouseDetail;


        public MutasiWarehouseWrapViewModel()
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                EditCommand = new DelegateCommand(Edit, CanEditCommand);
                DeleteCommand = new DelegateCommand(Delete, CanDeleteCommand);
                client = new MutasiWarehouseServicesClient();
                InventoryClient = new InventoryServiceClient();

                AddDetailCommand = new DelegateCommand(AddMutasiWarehouseDetail, CanAddDetailCommand);
                DeleteDetailCommand = new DelegateCommand(DeleteMutasiWarehouseDetail, CanDeleteDetailCommand);
                GetInventoryCommand = new DelegateCommand(GetInventory, CanGetInventoryCommand);
                GetQtyUnitCommand = new DelegateCommand(GetQtyUnit, CanGetQtyUnit);

                if (MutasiWarehouseViewModel.mode == Mode.Add || MutasiWarehouseViewModel.mode == Mode.Edit)
                {
                }
            }
        }

        public MutasiWarehouseViewModel MutasiWarehouseViewModel { get; set; }


        public ICommand EditCommand { get; set; }
        public ICommand DeleteCommand { get; set; }
        public ICommand AddDetailCommand { get; set; }
        public ICommand DeleteDetailCommand { get; set; }

        public ObservableCollection<InventoryDTO> Inventorys
        {
            get { return _Inventorys; }
            private set
            {
                if (Inventorys == value) return;
                _Inventorys = value;
                FirePropertyChanged("Inventorys");
            }
        }

        public MutasiWarehouseDetailDTO MutasiWarehouseDetail
        {
            get { return _MutasiWarehouseDetail; }
            set
            {
                if (MutasiWarehouseDetail == value) return;
                _MutasiWarehouseDetail = value;
                FirePropertyChanged("MutasiWarehouseDetail");
            }
        }

        public ICommand GetInventoryCommand { get; set; }
        public ICommand GetQtyUnitCommand { get; set; }

        public bool CanEditCommand(Object param)
        {
            return true;
        }

        public bool CanDeleteCommand(Object param)
        {
            return true;
        }

        public bool CanAddDetailCommand(Object param)
        {
            return true;
        }

        public bool CanDeleteDetailCommand(Object param)
        {
            return true;
        }


        public void Edit(Object param)
        {
            MutasiWarehouseViewModel.mode = Mode.Edit;
            Navigation.MyNavigation.Navigate(new Uri("/MutasiWarehouse/frmAdd", UriKind.Relative));
            Navigation.Args = param;
        }

        public void Delete(Object param)
        {
            DeleteConfirmation deleteConfirmation = new DeleteConfirmation();
            deleteConfirmation.Show();
            EventAggregator.RegisterMessage("ApprovalSucceeded", (x) =>
            {
                deleteConfirmation.Close();
                client.DeleteCompleted += client_DeleteCompleted;
                client.DeleteAsync((MutasiWarehouseDTO)param);
            });

        }

        private void client_DeleteCompleted(object sender, AsyncCompletedEventArgs e)
        {
            client.DeleteCompleted -= client_DeleteCompleted;
            MessageBox.Show("Delete Success!");
            MutasiWarehouseViewModel.mode = Mode.Idle;
            var VM = new MutasiWarehouseViewModel();
        }


        public void GetInventory(Object param)
        {
            MutasiWarehouseDetail = (MutasiWarehouseDetailDTO) param;
            string SerialNumber = MutasiWarehouseDetail.Inventory.SerialNumber;
            if (ValidSerialNumber(SerialNumber))
            {
                InventoryClient = new InventoryServiceClient();
                InventoryClient.GetInventoryCompleted += InventoryClient_GetInventoryCompleted;
                InventoryClient.GetInventoryAsync(SerialNumber);
            }
           
        }

        private void InventoryClient_GetInventoryCompleted(object sender, GetInventoryCompletedEventArgs e)
        {
            InventoryClient.GetInventoryCompleted -= InventoryClient_GetInventoryCompleted;

            //validasi
            InventoryDTO InventoryTemp = e.Result;
            if (InventoryTemp == null || string.IsNullOrEmpty(InventoryTemp.SerialNumber))
            {
                MessageBox.Show("Barang tidak ditemukan, coba entry secara manual");
                return;
            }

            try
            {
                MutasiWarehouseDetail.Inventory = e.Result;
                MutasiWarehouseDetail.Inventory.Item =
                    e.Result.Item;
                MutasiWarehouseDetail.Inventory.SatuanUnit =
                    e.Result.SatuanUnit;
                MutasiWarehouseDetail.Sheet = e.Result.Warehouses.FirstOrDefault
              (x => x.KodeWarehouse == MutasiWarehouseViewModel.MutasiWarehouse.FromWarehouse.KodeWarehouse).Sheet;
                MutasiWarehouseDetail.Qty = e.Result.Warehouses.FirstOrDefault
                (x => x.KodeWarehouse == MutasiWarehouseViewModel.MutasiWarehouse.FromWarehouse.KodeWarehouse).Qty;
                MutasiWarehouseDetail.Panjang = e.Result.Panjang;
                MutasiWarehouseDetail.Lebar = e.Result.Lebar;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Invalid Mutasi, Warehouse dan Stok tidak match!");
            }
          
           
        }

        private bool ValidSerialNumber(string SerialNumber)
        {
            if (MutasiWarehouseViewModel.MutasiWarehouse.MutasiWarehouseDetails.Count > 0 &&
                MutasiWarehouseViewModel.MutasiWarehouse.MutasiWarehouseDetails.Any(
                    x => x.Inventory.SerialNumber == SerialNumber && x.Inventory.Item != null))
            {
                MessageBox.Show("No.Log " + SerialNumber + " tidak valid!, Silahkan pilih yang lain!");
                return false;
            }
            return true;
        }


        public void AddMutasiWarehouseDetail(Object param)
        {
            MutasiWarehouseDetail = new MutasiWarehouseDetailDTO();
            MutasiWarehouseDetail.Inventory = new InventoryDTO();
            MutasiWarehouseViewModel.MutasiWarehouse.MutasiWarehouseDetails.Add(MutasiWarehouseDetail);
        }

        public void DeleteMutasiWarehouseDetail(Object param)
        {
            var MutasiWarehouseDetail = (MutasiWarehouseDetailDTO) param;
            if (MutasiWarehouseViewModel.MutasiWarehouse.MutasiWarehouseDetails.Count > 1)
            {
                if (param == null)
                {
                    int count = MutasiWarehouseViewModel.MutasiWarehouse.MutasiWarehouseDetails.Count;
                     MutasiWarehouseViewModel.MutasiWarehouse.MutasiWarehouseDetails.RemoveAt(count-1);
                }else
                {
                    MutasiWarehouseViewModel.MutasiWarehouse.MutasiWarehouseDetails.Remove(MutasiWarehouseDetail);
                }
            }
        }

      


        public bool CanGetInventoryCommand(Object param)
        {
            return true;
        }

        public bool CanGetQtyUnit(Object param)
        {
            return true;
        }

        public void GetQtyUnit(Object param)
        {
            MutasiWarehouseDetail = param as MutasiWarehouseDetailDTO;
            if (MutasiWarehouseDetail != null)
                if (MutasiWarehouseDetail.Inventory != null)
                    if (MutasiWarehouseDetail.Inventory.SatuanUnit != null)
                    {
                        MutasiWarehouseDetail.Qty = MutasiWarehouseDetail.Inventory.QtyPack *
                                                     (MutasiWarehouseDetail.Panjang *
                                                      MutasiWarehouseDetail.Lebar *
                                                      MutasiWarehouseDetail.Sheet) /
                                                     MutasiWarehouseDetail.Inventory.SatuanUnit.Pengali;
                        MutasiWarehouseDetail.Qty = MutasiWarehouseDetail.Inventory.Item.IsRounded
                                            ? MutasiWarehouseDetail.Qty.Round(2,MidpointRounding.AwayFromZero)
                                            : MutasiWarehouseDetail.Qty.Round(4, MidpointRounding.AwayFromZero);
                    }
                       

            

        }
    }
}